package home

import (
	"fmt"
	_ "github.com/astaxie/beego"
	//"log"
	"qinnailin.cn/cloudnote/controllers"
	"qinnailin.cn/cloudnote/models"
)

type GroupController struct {
	controllers.BaseController
}

//添加一条记录
func (this *GroupController) Add() {
	bean := &models.Group{Id: models.NewObjId(), Name: "默认"}
	child := &models.Group{Id: models.NewObjId(), Name: "默认子节点"}
	fmt.Println(child)
	bean.Cgroup = append(bean.Cgroup, *child)
	bean.Add()
	this.ToJson(bean, "保存成功！")
}

//获取文章分类列表
func (this *GroupController) GetGList() {
	bean := &models.Group{}
	list := bean.Query()
	this.ToJson(list)
}

//保持分组数据
func (this *GroupController) Save() {
	pid := this.GetString("pid")
	id := this.GetString("id")
	name := this.GetString("name")
	var pbean *models.Group
	if pid != "" && pid != "0" {
		pbean = &models.Group{Id: pid}
		err := pbean.Get()
		if err != nil {
			fmt.Println("pid:", pid, "id:", id, "name:", name, "数据获取失败！")
		} else {
			if id == "" {
				child := &models.Group{Id: models.NewObjId(), Name: name}
				pbean.Cgroup = append(pbean.Cgroup, *child)
			} else {
				for i := 0; i < len(pbean.Cgroup); i++ {
					if pbean.Cgroup[i].Id == id {
						pbean.Cgroup[i].Name = name
						break
					}
				}
			}
		}
		err = pbean.Update()
		if err != nil {
			this.ToJson(nil, "保存失败！")
		}
	} else {
		if id == "" {
			bean := &models.Group{Id: models.NewObjId(), Name: name}
			err := bean.Add()
			if err != nil {
				this.ToJson(nil, "保存失败！")
			}
		} else {
			bean := &models.Group{Id: id}
			err := bean.Get()
			if err != nil {
				fmt.Println("pid:", pid, "id:", id, "name:", name, "数据获取失败！")
			} else {
				bean.Name = name
				err = bean.Update()
				if err != nil {
					this.ToJson(nil, "保存失败！")
				}
			}
		}
	}
	this.ToJson("", "保存成功！")
}

//删除分组
func (this *GroupController) Remove() {
	pid := this.GetString("pid")
	id := this.GetString("id")
	var pbean *models.Group
	if pid != "" && pid != "0" {
		pbean = &models.Group{Id: pid}
		err := pbean.Get()
		if err != nil {
			fmt.Println("pid:", pid, "id:", id, "数据获取失败！")
		} else {
			arr := make([]models.Group, 0)
			for i := 0; i < len(pbean.Cgroup); i++ {
				if pbean.Cgroup[i].Id != id {
					arr = append(arr, pbean.Cgroup[i])
				}
			}
			pbean.Cgroup = arr
		}
		err = pbean.Update()
		if err != nil {
			this.ToJson(nil, "保存失败！")
		}
	} else {
		pbean = &models.Group{Id: id}
		err := pbean.Get()
		if err != nil {
			fmt.Println("pid:", pid, "id:", id, "数据获取失败！")
		}
		if len(pbean.Cgroup) > 0 {
			this.ToJson(nil, "存在子节点不能删除！")
		} else {
			err := pbean.Delete()
			if err != nil {
				this.ToJson(nil, "保存失败！")
			}
		}
	}
	this.ToJson("", "删除成功！")
}
